package xfyun

import (
	"encoding/json"
	"fmt"
	"io"
)

func ITR(data []byte) (res *ItrResult, e error) {
	requestBody := itrRequestBody{Data: data}
	req, e := requestBody.generateRequest()
	if e != nil {
		return nil, e
	}
	resp, e := client.Do(req)
	if e != nil {
		return nil, e
	}
	responseBody, _ := io.ReadAll(resp.Body)
	var r ItrResponseBody
	if len(responseBody) > 0 {
		if e := json.Unmarshal(responseBody, &r); e != nil {
			return nil, ErrServerResponseAnalyzeFailed
		}
	}
	if sc := resp.StatusCode; sc == 200 {
		if len(r.Data) == 0 {
			return nil, ErrServerResponseEmpty
		}
		rest := r.Data["ITRResult"]
		return &rest, nil
	} else if sc == 401 && r.Message == "Unauthorized" {
		return nil, ErrRequestAuthorizeEmpty
	} else if sc == 401 && r.Message == "HMAC signature cannot be verified" {
		return nil, ErrRequestAuthorizeInvalid
	} else if sc == 401 && r.Message == "HMAC signature does not match" {
		return nil, ErrRequestAuthorizeNotMatch
	} else if sc == 403 && r.Message == "HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication" {
		return nil, ErrRequestTimeNotMatch
	} else if sc == 403 && r.Message == "Your IP address is not allowed" {
		return nil, ErrRequestIPNotAllow
	} else {
		return nil, fmt.Errorf("系统错误[%d]，请联系管理员。", sc)
	}
}
